import { debounce } from '@/utils'
import echarts from 'echarts'

export default {
  computed: {
    /*  图表DOM  */
    $_chartMixin_chartWrapperDom () {
      const dom = document.getElementById(this.echartsId)
      return dom && echarts.init(dom)
    }
  },
  data () {
    return {
      $_sidebarElm: null,
      $_resizeHandler: null
    }
  },
  mounted () {
    this.initListener()
  },
  activated () {
    if (!this.$_resizeHandler) {
      // avoid duplication init
      this.initListener()
    }

    // when keep-alive chart activated, auto resize
    this.resize()
  },
  beforeDestroy () {
    this.destroyListener()
  },
  deactivated () {
    this.destroyListener()
  },
  methods: {
    // use $_ for mixins properties
    // https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential
    $_sidebarResizeHandler (e) {
      if (e.propertyName === 'width') {
        this.$_resizeHandler()
      }
    },
    initListener () {
      this.$_resizeHandler = debounce(() => {
        this.resize()
      }, 100)
      window.addEventListener('resize', this.$_resizeHandler)

      this.$_sidebarElm = document.getElementsByClassName('sidebar-container')[0]
      this.$_sidebarElm && this.$_sidebarElm.addEventListener('transitionend', this.$_sidebarResizeHandler)
    },
    destroyListener () {
      window.removeEventListener('resize', this.$_resizeHandler)
      this.$_resizeHandler = null
      this.$_chartMixin_chartWrapperDom.dispose()
      this.$_sidebarElm && this.$_sidebarElm.removeEventListener('transitionend', this.$_sidebarResizeHandler)
    },
    resize () {
      const { $_chartMixin_chartWrapperDom } = this
      $_chartMixin_chartWrapperDom && $_chartMixin_chartWrapperDom.resize()
    },
    $_chartMixin_init (options) {
      if (this.$_chartMixin_chartWrapperDom) {
        const that = this
        this.$_chartMixin_chartWrapperDom.clear() // 清空表格
        this.$_chartMixin_chartWrapperDom.showLoading() // 显示加载动画
        this.$_chartMixin_chartWrapperDom.setOption(options)
        this.$_chartMixin_chartWrapperDom.on('rendered', function () {
          that.$_chartMixin_chartWrapperDom.hideLoading()
        })
      }
    }
  }
}
